<template>
	<view class="edit-page">
		<view class="contentBox">
			<view class="form-title">基本信息</view>
			<view class="form-list">
				<view class="form-item">
					<view class="title required">房间</view>
					<view class="value-box">
						<view class="value-info">{{ dataForm.houseb_name }}</view>
					</view>
				</view>
				<view class="form-item">
					<view class="title required">房号</view>
					<view class="value-box">
						<view class="value-info">{{ dataForm.room_name }}</view>
					</view>
				</view>
				<view class="form-item">
					<view class="title required">起租日</view>
					{{ dataForm.start_time }}
					<!-- <view class="value-box" @click="showStartTime = true">
						<view class="value-info">{{ dataForm.start_time ? dataForm.start_time : '请选择' }}</view>
						<u-icon name="arrow-right" color="#000000"></u-icon>
					</view> -->
				</view>
				<view class="form-item">
					<view class="title required">到期日</view>
					{{ dataForm.end_time }}
					<!-- <view class="value-box" @click="showEndTime = true">
						<view class="value-info">{{ dataForm.end_time ? dataForm.end_time : '请选择' }}</view>
						<u-icon name="arrow-right" color="#000000"></u-icon>
					</view> -->
				</view>
				<view class="form-item">
					<view class="title required">房租</view>
					<input v-model="dataForm.money_zu" disabled placeholder="请输入房租" class="input" type="digit" />
					<view class="unit">元/月</view>
				</view>
				<view class="form-item">
					<view class="title required">押金</view>
					<view class="value-box">
						<view class="value-info">{{ dataForm.money_ya }}</view>
					</view>
				</view>
				<view class="form-item">
					<view class="title required">交租方式</view>
					{{ formatDataList(dataForm.rent_way, rentWayList[0]) }}
					<!-- <view class="value-box" @click="showRentWay = true">
						<view class="value-info">
							{{ dataForm.rent_way ? formatDataList(dataForm.rent_way, rentWayList[0]) : '请选择' }}
						</view>
						<view class="unit">一交</view>
					</view> -->
				</view>
				<!-- <view class="form-item">
					<view class="title required">交租日</view>
					<view class="value-box" @click="showRentDay = true">
						<view class="value-info">
							{{ dataForm.rent_day ? formatDataList(dataForm.rent_day, rentDayList[0]) : '请选择' }}
						</view>
						<u-icon name="arrow-right" color="#000000"></u-icon>
					</view>
				</view> -->
				<!-- <view class="form-item">
					<view class="title">提前</view>
					<view class="value-box">
						<input v-model="dataForm.ahead_day" placeholder="请输入提前天数" class="input" type="digit" />
						<view class="unit">天交租</view>
					</view>
				</view> -->
			</view>
			<view class="form-title">租客信息</view>
			<view class="form-list">
				<!-- <view class="form-item">
					<view class="title required">类型</view>
					<view class="value-box" @click="showUserType = true">
						<view class="value-info">
							{{ dataForm.user_type ? formatDataList(dataForm.user_type, usertypeList[0]) : '请选择' }}
						</view>
						<u-icon name="arrow-right" color="#000000"></u-icon>
					</view>
				</view> -->
				<view class="form-item">
					<view class="title required">姓名</view>
					<view class="value-box">
						<view class="value-info">
							<input v-model="dataForm.user_name" disabled placeholder="请输入姓名" class="input" />
						</view>
						<!-- <view @click="$Tips('/pages-landlord/customer/index?pageType=select')">
							<u-icon name="arrow-right" color="#000000"></u-icon>
						</view> -->
					</view>
				</view>
				<!-- <view class="form-item" v-if="dataForm.user_type == 2">
					<view class="title required">名称</view>
					<view class="value-box">
						<view class="value-info">
							<input v-model="dataForm.user_name" placeholder="请输入名称" class="input" />
						</view>
						<view @click="$Tips('/pages-landlord/customer/index?pageType=select')">
							<u-icon name="arrow-right" color="#000000"></u-icon>
						</view>
					</view>
				</view> -->
				<!-- <view class="form-item" v-if="dataForm.user_type == 2">
					<view class="title">联系人</view>
					<view class="value-box">
						<input v-model="dataForm.contact_name" placeholder="请输入联系人" class="input" />
					</view>
				</view> -->
				<!-- <view class="form-item">
					<view class="title required">性别</view>
					<view class="value-box" @click="showSex = true">
						<view class="value-info">{{ dataForm.sex ? formatDataList(dataForm.sex, sexList[0]) : '请选择' }}
						</view>
						<u-icon name="arrow-right" color="#000000"></u-icon>
					</view>
				</view> -->
				<view class="form-item">
					<view class="title">电话</view>
					<view class="value-box">
						<input v-model="dataForm.user_phone" disabled placeholder="请输入内容" class="input" />
					</view>
				</view>
				<view class="form-item">
					<view class="title">证件号</view>
					<view class="value-box">
						<input v-model="dataForm.user_card" disabled placeholder="请输入内容" class="input" />
					</view>
				</view>
				<view class="form-item1">
					<view class="title">证件&合同照片</view>
					<view style="margin-top: 20rpx">
						<image :src="dataForm.user_card_img" mode="widthFix" style="width: 144rpx; height: 144rpx">
						</image>
						<!-- <u-upload :fileList="fileList" @afterRead="afterRead" @delete="deletePic" name="1" multiple
							:maxCount="8" width="144rpx" height="144rpx">
							<image src="../static/images/tp.png" mode="widthFix" style="width: 144rpx; height: 144rpx">
							</image>
						</u-upload> -->
					</view>
				</view>
				<!-- <view class="form-item">
					<view class="title">租客签名</view>
					<view class="value-box" @click="handleSign">
						<view class="value-info">{{ dataForm.user_sign_img ? '修改签名' : '点击签名' }}</view>
						<u-icon name="arrow-right" color="#000000"></u-icon>
					</view>
				</view> -->
				<!-- <view class="form-item1" v-if="dataForm.user_sign_img">
					<view style="margin-top: 20rpx">
						<image :src="dataForm.user_sign_img" mode="widthFix" style="width: 144rpx;height: 144rpx;">
						</image>
					</view>
				</view> -->
			</view>
			<view class="select-box">
				<view class="select-title">
					<view class="title">水电表</view>
					<!-- <image src="/pages-landlord/static/room/select-add.png" class="icon-select"
						@click="selectMeterInfo"></image> -->
				</view>
				<view class="select-list">
					<view class="select-item" v-for="(item, index) in dataForm.board" :key="item.name"
						@click="updateMeterInfo(item)">
						<view class="item-left">{{ item.name }}</view>
						<view class="item-right">
							<view class="item-text">({{ item.last_num }} - {{ item.min_num }})*{{ item.price }} {{
								meterUnitFormat(item.type) }}</view>
							<u-icon name="arrow-right" color="#000000"></u-icon>
						</view>
					</view>
				</view>
			</view>
			<view class="select-box">
				<view class="select-title">
					<view class="title">应退{{ tktotal == 0 ? '' : tktotal.toFixed(2) }}元</view>
					<image src="/pages-landlord/static/room/select-add.png" class="icon-select"
						@click="selectFixedCosts"></image>
				</view>
				<view class="select-list">
					<view class="select-item" v-for="(item, index) in dataForm.fixed" :key="index"
						@click="updateFixedCosts(item)">
						<view class="item-left">{{ item.type_name }}</view>
						<view class="item-right">
							<view class="item-text">{{ item.price }} {{ fixedUnitFormat(item.date_type) }}</view>
							<u-icon name="arrow-right" color="#000000"></u-icon>
						</view>
					</view>
				</view>
			</view>
			<view class="select-box">
				<view class="select-title">
					<view class="title">应扣{{ kktotal == 0 ? '' : kktotal.toFixed(2) }}元</view>
					<image src="/pages-landlord/static/room/select-add.png" class="icon-select"
						@click="selectFixedCostss"></image>
				</view>
				<view class="select-list">
					<view class="select-item" @click="showModalSD">
						<view class="item-left">水电费</view>
						<view class="item-right">
							<view class="item-text">{{ sdpprice.toFixed(2) }}</view>
							<!-- <u-icon name="arrow-right" color="#000000"></u-icon> -->
						</view>
					</view>
					<view class="select-item" v-for="(item, index) in dataForm.fixeds" :key="index"
						@click="updateFixedCostss(item)">
						<view class="item-left">{{ item.type_name }}</view>
						<view class="item-right">
							<view class="item-text">{{ item.price }} {{ fixedUnitFormat(item.date_type) }}</view>
							<u-icon name="arrow-right" color="#000000"></u-icon>
						</view>
					</view>
				</view>
			</view>
			<view class="select-box">
				<view class="select-title">
					<view class="title">设备及押金</view>
				</view>
				<view style="display: flex;flex-wrap: wrap;">
					<u-tag style="padding: 5rpx;" plain shape="circle" :text="`${item.name} ${item.deposit}元`"
						v-for="(item, index) in dataForm.pt" :key="index"></u-tag>
				</view>
				<!-- <view class="select-list"> -->
				<!-- <u-tag :text="`${item.name} ${item.deposit}元`" v-for="(item, index) in dataForm.pt" :key="index"></u-tag> -->
				<!-- @click="updateSupportInfo(item)" -->
				<!-- <view class="select-item" v-for="(item, index) in dataForm.pt" :key="index"> -->
				<!-- <view class="item-left">{{ item.name }}</view> -->
				<!-- <view class="item-right"> -->
				<!-- <view class="item-text">{{ item.deposit }}元</view> -->
				<!-- <u-icon name="arrow-right" color="#000000"></u-icon> -->
				<!-- </view> -->
				<!-- </view> -->
				<!-- </view> -->
			</view>
			<view class="form-title">合计退款 {{ totalCost.toFixed(2) }} 元</view>
			<view class="form-list">
				<view class="form-item">
					<view class="title required">退房日期</view>
					<view class="value-box" @click="showStartTime = true">
						<view class="value-info">{{ dataForm.start_time ? dataForm.start_time : '请选择' }}</view>
						<u-icon name="arrow-right" color="#000000"></u-icon>
					</view>
				</view>
				<view class="form-item">
					<view class="title required">退款方式</view>
					<view class="value-box" @click="showRentWay = true">
						<view class="value-info">
							{{ dataForm.rent_way ? formatDataList(dataForm.tk_type, rentWayLists[0]) : '请选择' }}
						</view>
					</view>
				</view>
				<!-- <view class="form-item">
					<view class="title">固定费用</view>
					<view class="value-box">
						<view class="value-info">{{ fixedCosts }}</view>
						<view class="unit">元</view>
					</view>
				</view> -->
				<!--				<view class="form-item">-->
				<!--					<view class="title">设备押金</view>-->
				<!--					<view class="value-box">-->
				<!--						<view class="value-info">{{deviceDeposit}}</view>-->
				<!--						<view class="unit">元</view>-->
				<!--					</view>-->
				<!--				</view>-->
				<view class="form-item">
					<view class="title">备注</view>
					<view class="value-box">
						<input v-model="dataForm.remark" placeholder="请输入内容" class="input" />
					</view>
				</view>
			</view>

			<view class="fillBox" style="height: 150rpx;"></view>
			<view class="safe-bottom page-bottom">
				<!-- <view class="icon-box" @click="handleMore" v-if="contract_id">
					<u-icon name="grid" size="20" color="#444444"></u-icon>
					<view class="label">更多</view>
				</view> -->
				<view class="action-btn-group">
					<view class="action-btn1" @click="cancelSave">取消</view>
					<view class="action-btn2" @click="saveRefund">确定退租
					</view>
					<!-- <view class="action-btn2" @click="$u.throttle(contractRevoke, 2000)"
						v-if="contract_id!=''&&dataForm.status===3">提醒
					</view> -->
				</view>
			</view>
		</view>
		<u-datetime-picker :show="showStartTime" v-model="startTime" mode="date" closeOnClickOverlay
			@confirm="confirmStartDate" @change="changeStartDate" @cancel="showStartTime = false"></u-datetime-picker>
		<u-datetime-picker :show="showEndTime" v-model="endTime" mode="date" closeOnClickOverlay
			@confirm="confirmEndDate" @change="changeEndDate" @cancel="showEndTime = false"></u-datetime-picker>
		<u-picker :show="showRentWay" :columns="rentWayLists" keyName="name" @cancel="showRentWay = false"
			@confirm="confirmSelectRentType"></u-picker>
		<u-picker :show="showRentDay" :columns="rentDayList" keyName="name" @cancel="showRentDay = false"
			@confirm="confirmSelectRentDay"></u-picker>
		<u-picker :show="showUserType" :columns="usertypeList" keyName="name" @cancel="showUserType = false"
			@confirm="confirmSelectUserType"></u-picker>
		<u-picker :show="showSex" :columns="sexList" keyName="name" @cancel="showSex = false"
			@confirm="confirmSelectSex"></u-picker>
	</view>
</template>

<script>
import {
	contractAdd,
	roomDetail,
	contractEdit,
	contractDetail,
	contractAudit,
	contractDel,
	contractRevokeAudit,
	tkDetail,
	pushContractTk,
	getBoards
	// getContractFixed
} from '@/api/landlord'
import {
	getUserInfo,
} from '@/api/mine.js'
// 定义事件名称常量（避免魔法字符串）
const EVENT_TYPES = {
	SIGNATURE_INFO: 'signatureComplete',
	CUSTOMER_INFO: 'customerSelected',
	METER_SELECT: 'selectRoomMeterInfo',
	METER_DELETE: 'deleteRoomMeterInfo',
	FIXED_COST_SELECT: 'selectRoomFixedCosts',
	FIXED_COST_SELECTS: 'selectRoomFixedCostss',
	FIXED_COST_DELETE: 'deleteRoomFixedCosts',
	FIXED_COST_DELETES: 'deleteRoomFixedCostss',
	SUPPORT_SELECT: 'selectRoomSupportInfo',
	SUPPORT_DELETE: 'deleteRoomSupportInfo'
};
export default {
	computed: {
		deviceDeposit() {
			if (!this.dataForm.pt || !Array.isArray(this.dataForm.pt)) {
				return 0;
			}
			return this.dataForm.pt.reduce((total, item) => {
				return total + (Number(item.deposit) || 0);
			}, 0);
		},
		fixedCosts() {
			if (!this.dataForm.fixed || !Array.isArray(this.dataForm.fixed)) {
				return 0;
			}
			return this.dataForm.fixed.reduce((total, item) => {
				return total + (Number(item.price) || 0);
			}, 0);
		},
		sdpprice() {
			let c = this.dataForm.board.reduce((total, item) => {
				return total + (Number(item.price) * (Number(item.last_num) - Number(item.min_num)) || 0);
			}, 0);
			return c;
		},
		kktotal() {
			let c = this.dataForm.board.reduce((total, item) => {
				return total + (Number(item.price) * (Number(item.last_num) - Number(item.min_num)) || 0);
			}, 0);
			if (!this.dataForm.fixeds || !Array.isArray(this.dataForm.fixeds)) {
				return 0 + c;
			}
			let a = this.dataForm.fixeds.reduce((total, item) => {
				return total + (Number(item.price) || 0);
			}, 0);
			return a + c;
		},
		tktotal() {
			if (!this.dataForm.fixed || !Array.isArray(this.dataForm.fixed)) {
				return 0;
			}
			let b = this.dataForm.fixed.reduce((total, item) => {
				return total + (Number(item.price) || 0);
			}, 0);
			return b;
		},
		totalCost() {
			let a = this.dataForm.fixeds.reduce((total, item) => {
				return total + (Number(item.price) || 0);
			}, 0);
			let b = this.dataForm.fixed.reduce((total, item) => {
				return total + (Number(item.price) || 0);
			}, 0);
			let c = this.dataForm.board.reduce((total, item) => {
				return total + (Number(item.price) * (Number(item.last_num) - Number(item.min_num)) || 0);
			}, 0);
			return (b - a - c)
			// + Number(this.fixedCosts) + Number(this.deviceDeposit);
		}
	},
	data() {
		return {
			userinfo: null, //用户信息
			showPopup: false, // 是否显示筛选弹窗
			room_id: '', // 房间ID
			contract_id: '', // 合同ID
			roomAddress: '', // 房间地址
			dataForm: {
				room_id: '',
				start_time: '',
				end_time: '',
				date_type: '', // 1一年 2半年 3三个月 4两个月 5一个月
				money_zu: '',
				money_ya: '',
				rent_type: 1,
				tk_type: 1,
				rent_day: 10,
				ahead_day: 1,
				user_type: 1,
				user_name: '',
				contact_name: '',
				sex: 1,
				user_phone: '',
				user_card: '',
				user_sign_img: '',
				first_zu: '',
				remark: '',
				pt: [],
				board: [],
				fixed: [],
				fixeds: [],
			},
			dateTypeList: [{
				name: '一年',
				type: 1
			},
			{
				name: '半年',
				type: 2
			},
			{
				name: '三个月',
				type: 3
			},
			{
				name: '两个月',
				type: 4
			},
			{
				name: '一个月',
				type: 5
			}
			],
			startTime: '',
			showStartTime: false,
			endTime: '',
			showEndTime: false,
			showRentWay: false,
			rentWayLists: [[
				{
					name: '现金支付',
					type: 1
				},
				{
					name: '微信转账',
					type: 2
				},
				{
					name: '支付宝转账',
					type: 3
				},
				{
					name: '微信扫码',
					type: 4
				},
				{
					name: '支付宝扫码',
					type: 5
				},]
			],
			rentWayList: [
				[{
					name: '每月',
					type: 1
				},
				{
					name: '2个月',
					type: 2
				},
				{
					name: '3个月',
					type: 3
				},
					// {
					// 	name: '半年',
					// 	type: 4
					// },
					// {
					// 	name: '一年',
					// 	type: 5
					// },
					// {
					// 	name: '日租',
					// 	type: 6
					// },
					// {
					// 	name: '分期',
					// 	type: 7
					// },
					// {
					// 	name: '其他',
					// 	type: 8
					// }
				]
			],
			showRentDay: false,
			rentDayList: [
				[{
					name: '1号',
					type: 1
				}, {
					name: '2号',
					type: 2
				}, {
					name: '3号',
					type: 3
				}, {
					name: '4号',
					type: 4
				}, {
					name: '5号',
					type: 5
				}, {
					name: '6号',
					type: 6
				}, {
					name: '7号',
					type: 7
				}, {
					name: '8号',
					type: 8
				}, {
					name: '9号',
					type: 9
				}, {
					name: '10号',
					type: 10
				}, {
					name: '11号',
					type: 11
				}, {
					name: '12号',
					type: 12
				}, {
					name: '13号',
					type: 13
				}, {
					name: '14号',
					type: 14
				}, {
					name: '15号',
					type: 15
				}, {
					name: '16号',
					type: 16
				}, {
					name: '17号',
					type: 17
				}, {
					name: '18号',
					type: 18
				}, {
					name: '19号',
					type: 19
				}, {
					name: '20号',
					type: 20
				},
				{
					name: '21号',
					type: 21
				}, {
					name: '22号',
					type: 22
				}, {
					name: '23号',
					type: 23
				}, {
					name: '24号',
					type: 24
				}, {
					name: '25号',
					type: 25
				}, {
					name: '26号',
					type: 26
				}, {
					name: '27号',
					type: 27
				}, {
					name: '28号',
					type: 28
				}, {
					name: '29号',
					type: 29
				}, {
					name: '30号',
					type: 30
				}, {
					name: '31号',
					type: 31
				}
				]
			],
			showUserType: false,
			usertypeList: [
				[{
					name: '个人',
					type: 1
				},
				{
					name: '企业',
					type: 2
				}
				]
			],
			showSex: false,
			sexList: [
				[{
					name: '男',
					type: 1
				},
				{
					name: '女',
					type: 2
				}
				]
			],
			fileList: [],
			isRenewal: false,
			original_end_time: ''
		}
	},
	onLoad(options) {
		// getContractFixed().then(res => {
		// 	console.log(res);
		// })
		if (options && options.room_id) {
			this.room_id = options.room_id
			this.getRoomDetail()
		}
		if (options && options.contract_id) {
			this.contract_id = options.contract_id
			this.getContractDetail()
		}
		this.getUserInfo()
	},
	onShow() {
		this.initEventListeners()
	},
	methods: {
		showModalSD() {
			uni.showModal({
				title: '提示',
				content: '请前往水电表栏修改水电费',
				showCancel: false,
			});
		},
		saveRefund() {
			// console.log(this.dataForm);
			let data = {
				contract_id: this.contract_id,
				t_data: this.dataForm.fixed.map(e => {
					return {
						name: e.type_name,
						value: e.price,
					}
				}),
				f_data: [...this.dataForm.fixeds, ...[{
					type_name: '水电费',
					price: this.sdpprice,
				}]].map(e => {
					return {
						name: e.type_name,
						value: e.price,
					}
				}),
				end_money: this.totalCost.toFixed(2),
				tk_date: this.dataForm.start_time,
				tk_type: this.dataForm.tk_type,
				remarks: this.dataForm.remark
			}
			// console.log(data)
			uni.showModal({
				title: '提示',
				content: `应退还租客${this.totalCost.toFixed(2)}元,确定退房吗？`,
				showCancel: true,
				success: ({ confirm, cancel }) => {
					if (confirm) {
						pushContractTk(data).then(res => {
							uni.showModal({
								title: '退房成功',
								content: '已生成一张待支付订单，是否前往查看',
								showCancel: true,
								cancelText: '返回',
								success: ({ confirm, cancel }) => {
									if (confirm) {
										uni.navigateTo({ url: '/pages-landlord/house/receiptNew' })

									}
									if (cancel) {
										uni.navigateBack({
											delta: 1
										})
									}
								}
							})
						});
					}
				}
			})

		},
		contractRevoke() {
			contractRevokeAudit({
				contract_id: this.contract_id
			}).then(res => {
				this.$Tips({
					title: '撤回成功'
				}, {
					url: '1',
					tab: 3
				});
			});
		},
		handleMore() {
			let that = this
			let itemList = []
			if (this.dataForm.status === 0) {
				itemList = ['删除合同', '更换租客', '续租', '退租']
			} else {
				itemList = ['删除合同', '更换租客', '续租', '退租', '租客换房']
			}
			uni.showActionSheet({
				// '历史账单', '历史合同', '收支明细', '操作记录',
				itemList: itemList,
				success(res) {
					switch (res.tapIndex) {
						case 0:
							uni.showModal({
								confirmColor: "#FE4F04",
								content: "确定删除该合同吗？",
								success(res) {
									if (res.confirm) {
										contractDel({
											ids: that.contract_id
										}).then(res => {
											that.$Tips({
												title: '删除合同成功'
											}, {
												url: '1',
												tab: 3
											});
										});
									}
								}
							})
							break;
						case 1:
							that.dataForm.user_type = 1
							that.dataForm.user_name = ''
							that.dataForm.contact_name = ''
							that.dataForm.sex = 1
							that.dataForm.user_phone = ''
							that.dataForm.user_card = ''
							that.dataForm.user_sign_img = ''
							break;
						case 2:
							that.original_end_time = that.dataForm.end_time
							that.isRenewal = true
							that.selectDateType(1)
							break;
						case 3:
							// that.$Toast('功能开发中')
							uni.navigateTo({
								url: `/pages-landlord/room-manage/rental-refund?contract_id=${that.contract_id}&room_id=${that.room_id}`
							})
							break;
						case 4:
							that.$Toast('功能开发中')
							break;
						default:
					}
				}
			})
		},
		contractAudit() {
			contractAudit({
				id: this.contract_id
			}).then(res => {
				this.$Tips({
					title: '合同审核成功'
				}, {
					url: '1',
					tab: 3
				});
			});
		},
		getUserInfo() {
			getUserInfo().then(res => {
				this.userinfo = res.data.data.userinfo
			})
		},
		selectDateType(item) {
			if (!this.isRenewal) return
			this.dataForm.date_type = item.type;
			this.$nextTick(() => {
				//根据选择的日期类型以起租日时间戳设置到期日时间戳
				if (item.type == 1) {
					this.endTime = new Date(new Date(this.original_end_time).setFullYear(new Date(this.original_end_time)
						.getFullYear() + 1));
				} else if (item.type == 2) {
					this.endTime = new Date(new Date(this.original_end_time).setMonth(new Date(this.original_end_time)
						.getMonth() + 6));
				} else if (item.type == 3) {
					this.endTime = new Date(new Date(this.original_end_time).setMonth(new Date(this.original_end_time)
						.getMonth() + 3));
				} else if (item.type == 4) {
					this.endTime = new Date(new Date(this.original_end_time).setMonth(new Date(this.original_end_time)
						.getMonth() + 2));
				} else if (item.type == 5) {
					this.endTime = new Date(new Date(this.original_end_time).setMonth(new Date(this.original_end_time)
						.getMonth() + 1));
				}
				this.dataForm.end_time = uni.$u.timeFormat(this.endTime, 'yyyy-mm-dd');
			})
		},
		changeStartDate(e) {
			this.startTime = e.value; // 更新选择的日期
		},
		confirmStartDate(e) {
			this.showStartTime = false; // 关闭选择器
			this.dataForm.date_type = ''
			this.dataForm.start_time = uni.$u.timeFormat(e.value, 'yyyy-mm-dd');
		},
		changeEndDate(e) {
			this.endTime = e.value; // 更新选择的日期
		},
		confirmEndDate(e) {
			this.showEndTime = false; // 关闭选择器
			this.dataForm.date_type = ''
			this.dataForm.end_time = uni.$u.timeFormat(e.value, 'yyyy-mm-dd');
		},
		formatDataList(data, list) {
			if (!data || !list || !Array.isArray(list)) {
				return '';
			}
			const item = list.find(item => item.type == data);
			return item ? item.name : '';
		},
		confirmSelectRentType(event) {
			this.dataForm.tk_type = event.value[0].type;
			this.showRentWay = false;
		},
		confirmSelectRentDay(event) {
			this.dataForm.rent_day = event.value[0].type;
			this.showRentDay = false;
		},
		confirmSelectUserType(event) {
			this.dataForm.user_type = event.value[0].type;
			if (this.dataForm.user_type === 1) {
				this.dataForm.contact_name = '';
			} else {
				this.dataForm.user_name = '';
			}
			this.showUserType = false;
		},
		confirmSelectSex(event) {
			this.dataForm.sex = event.value[0].type;
			this.showSex = false;
		},
		handleSign() {
			uni.navigateTo({
				url: "/pages-landlord/signature-page/signature-page"
			})
		},
		// 删除图片
		deletePic(event) {
			this.fileList.splice(event.index, 1);
		},
		// 新增图片
		async afterRead(event) {
			// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
			let lists = [].concat(event.file);
			let fileListLen = this.fileList.length;
			lists.map((item) => {
				this.fileList.push({
					...item,
					status: "uploading",
					message: "上传中",
				});
			});
			for (let i = 0; i < lists.length; i++) {
				const result = await this.$uploadFilePromise(lists[i].url);
				let item = this.fileList[fileListLen];
				this.fileList.splice(
					fileListLen,
					1,
					Object.assign(item, {
						status: "success",
						message: "",
						url: result.fullurl,
						img: result.url
					})
				);
				fileListLen++;
			}
		},
		// 获取房间详情
		getRoomDetail() {
			roomDetail({
				id: this.room_id
			}).then(res => {
				console.log(res);
				this.dataForm.room_id = this.room_id
				if (this.dataForm.contract_id) {
					this.contract_id = this.dataForm.contract_id
					this.getContractDetail()
				} else {
					this.roomAddress = res.data.data.building.name + res.data.data.name
					this.dataForm.money_zu = res.data.data.price
					// this.dataForm.money_ya = res.data.data.price
					this.dataForm.pt = res.data.data.pt || [];
					this.dataForm.board = res.data.data.board || [];
					this.dataForm.fixed = res.data.data.fixed || [];
					// 设置起租日和到期日
					if (!res.data.data.start_time && !res.data.data.end_time) {
						this.dataForm.date_type = 1
						this.startTime = new Date()
						this.dataForm.start_time = uni.$u.timeFormat(this.startTime, 'yyyy-mm-dd');
						this.endTime = new Date(new Date().setFullYear(new Date().getFullYear() + 1));
						this.dataForm.end_time = uni.$u.timeFormat(this.endTime, 'yyyy-mm-dd');
					}
					if (this.dataForm.images) {
						this.fileList = this.dataForm.images.split(',').map(item => ({
							// url: this.$OssUrl(item),
							url: item,
							img: item,
						}));
					}
				}
			})
		},
		// 获取合同详情
		getContractDetail() {
			contractDetail({
				id: this.contract_id
			}).then(ress => {
				this.dataForm.board = ress.data.data.board || [];
				this.dataForm.pt = ress.data.data.pt || [];
				// this.dataForm.fixed = ress.data.data.fixed || [];
				tkDetail({
					contract_id: this.contract_id
				}).then(res => {
					this.roomAddress = res.data.data.build_name + res.data.data.room_name
					this.dataForm.room_name = res.data.data.room_name
					this.dataForm.houseb_name = res.data.data.houseb_name
					this.dataForm.start_time = res.data.data.start_time
					this.dataForm.end_time = res.data.data.end_time
					this.dataForm.money_zu = res.data.data.money_zu
					this.dataForm.rent_way = res.data.data.rent_way
					this.dataForm.user_name = res.data.data.user_name
					this.dataForm.user_phone = res.data.data.user_phone
					this.dataForm.user_card = res.data.data.user_card
					this.dataForm.user_card_img = res.data.data.user_card_img
					this.dataForm.money_electricity = res.data.data.money_electricity
					this.dataForm.money_water = res.data.data.money_water
					this.dataForm.money_ya = res.data.data.money_ya
					this.dataForm.pt.unshift({
						name: '押金',
						deposit: res.data.data.money_ya
					})
				})
			})


		},
		// 处理签名选择
		handleSignatureInfo(signInfo) {
			if (signInfo) {
				this.dataForm.user_sign_img = signInfo.fullurl;
				this.$forceUpdate()
			}
		},
		// 处理客户信息选择
		handleCustomerInfo(customerInfo) {
			if (customerInfo) {
				this.dataForm.user_type = customerInfo.type || 1; // 默认个人
				this.dataForm.user_name = customerInfo.name;
				this.dataForm.user_card = customerInfo.id_card || '';
				this.dataForm.sex = customerInfo.sex
				this.dataForm.user_phone = customerInfo.mobile;
				this.dataForm.contact_name = customerInfo.contact_name || '';
				if (customerInfo.card_image) {
					this.fileList = customerInfo.card_image.split(',').map(item => {
						return {
							url: item,
							img: item
						}
					})
				}
			}
		},
		// 初始化事件监听
		initEventListeners() {
			// 监听签名完成事件
			uni.$on(EVENT_TYPES.SIGNATURE_INFO, (data) => this.handleSignatureInfo(data));

			// 选择客户信息
			uni.$on(EVENT_TYPES.CUSTOMER_INFO, (data) => this.handleCustomerInfo(data));

			// 水电表管理
			uni.$on(EVENT_TYPES.METER_SELECT, (data) => this.handleItemUpdate(data, 'board', 'name'));
			uni.$on(
				EVENT_TYPES.METER_DELETE, (data) => this.handleItemDelete(data, 'board', 'name'));

			// 固定费用管理
			uni.$on(EVENT_TYPES.FIXED_COST_SELECT, (data) => this.handleItemUpdate(data, 'fixed',
				'type_name'));
			uni.$on(EVENT_TYPES.FIXED_COST_SELECTS, (data) => this.handleItemUpdate(data, 'fixeds',
				'type_name'));
			uni.$on(EVENT_TYPES.FIXED_COST_DELETE, (data) => this.handleItemDelete(data,
				'fixed', 'type_name'));
			uni.$on(EVENT_TYPES.FIXED_COST_DELETES, (data) => this.handleItemDelete(data,
				'fixeds', 'type_name'));

			// 配套设备管理
			uni.$on(EVENT_TYPES.SUPPORT_SELECT, (data) => this.handleItemUpdate(data, 'pt', 'name'));
			uni.$on(
				EVENT_TYPES.SUPPORT_DELETE, (data) => this.handleItemDelete(data, 'pt', 'name'));

		},
		// 移除事件监听
		removeEventListeners() {
			uni.$off(EVENT_TYPES.SIGNATURE_INFO);
			uni.$off(EVENT_TYPES.METER_SELECT);
			uni.$off(EVENT_TYPES.METER_DELETE);
			uni.$off(EVENT_TYPES.FIXED_COST_SELECT);
			uni.$off(EVENT_TYPES.FIXED_COST_DELETE);
			uni.$off(EVENT_TYPES.SUPPORT_SELECT);
			uni.$off(EVENT_TYPES.SUPPORT_DELETE);
		},
		/**
		 * 通用更新/添加逻辑
		 * @param {Object} data 新数据
		 * @param {String} arrayKey dataForm 中的数组键名
		 * @param {String} matchKey 匹配字段名
		 */
		handleItemUpdate(data, arrayKey, matchKey) {

			if (!data) return;

			// 使用 findIndex 查找是否已存在
			const existingIndex = this.dataForm[arrayKey].findIndex(
				item => item[matchKey] === data[matchKey]
			);
			// 存在则更新，不存在则添加
			if (existingIndex !== -1) {
				// UniApp 中直接修改数组元素通常是响应式的
				this.dataForm[arrayKey].splice(existingIndex, 1, data);
			} else {
				this.dataForm[arrayKey].push(data);
			}
			this.removeEventListeners();
		},

		/**
		 * 通用删除逻辑
		 * @param {Object} data 要删除的数据（只需包含匹配字段）
		 * @param {String} arrayKey dataForm 中的数组键名
		 * @param {String} matchKey 匹配字段名
		 */
		handleItemDelete(data, arrayKey, matchKey) {
			if (!data) return;

			const index = this.dataForm[arrayKey].findIndex(
				item => item[matchKey] === data[matchKey]
			);

			if (index !== -1) {
				this.dataForm[arrayKey].splice(index, 1);
			}
			this.removeEventListeners()
		},
		selectMeterInfo() {
			uni.navigateTo({
				url: '/pages-landlord/room-manage/instrument-details'
			})
		},
		updateMeterInfo(item) {
			uni.navigateTo({
				url: '/pages-landlord/room-manage/instrument-details-refund?dataInfo=' + JSON.stringify(item)
			})
		},
		meterUnitFormat(type) {
			switch (type) {
				case 1:
					return '元/吨';
				case 2:
					return '元/度';
				case 3:
					return '元/立方米';
				case 4:
					return '元/升';
				default:
					return '';
			}
		},
		selectFixedCosts() {
			uni.navigateTo({
				url: '/pages-landlord/room-manage/fixed-costs-refund'
			})
		},
		selectFixedCostss() {
			uni.navigateTo({
				url: '/pages-landlord/room-manage/fixed-costs-refund?type=1'
			})
		},
		updateFixedCosts(item) {
			uni.navigateTo({
				url: '/pages-landlord/room-manage/fixed-costs-refund?dataInfo=' + JSON.stringify(item)
			})
		},
		updateFixedCostss(item) {
			uni.navigateTo({
				url: '/pages-landlord/room-manage/fixed-costs-refund?type=1&dataInfo=' + JSON.stringify(item)
			})
		},
		fixedUnitFormat(type) {
			switch (type) {
				case 1:
					return '随房租付';
				case 2:
					return '元/年';
				case 3:
					return '元/半年';
				case 4:
					return '一次性付';
				case 5:
					return '元/月';
				case 6:
					return '元/季';
				default:
					return '';
			}
		},
		selectSupportInfo() {
			uni.navigateTo({
				url: '/pages-landlord/room-manage/support-detail'
			})
		},
		updateSupportInfo(item) {
			uni.navigateTo({
				url: '/pages-landlord/room-manage/support-detail?dataInfo=' + JSON.stringify(item)
			})
		},
		// 提交信息
		confirmSave() {
			let dataForm = this.formatFormData()
			if (!this.contract_id) {
				contractAdd({
					...dataForm,
					user_card_img: this.fileList.map(item => item.url).join(','),
				}).then(res => {
					this.contract_id = res.data.data.contract_id
					this.getContractDetail()
					this.toContractlist()
				})
			} else {
				contractEdit({
					...dataForm,
					user_card_img: this.fileList.map(item => item.url).join(','),
				}).then(res => {
					this.getContractDetail()
					this.toContractlist()
				})
			}

		},
		toContractlist() {
			let that = this
			uni.showModal({
				confirmColor: "#FE4F04",
				cancelText: '返回',
				content: "合同创建成功，是否前往合同列表？",
				success(res) {
					if (res.confirm) {
						uni.redirectTo({
							url: '/pages-landlord/contract/contractList'
						})
					}
				}
			})
		},
		// 格式化表单数据,判断meter、fixed、pt是否存在里的对象中是否包含id和room_id字段，如果存在则删除
		formatFormData() {
			let formData = JSON.parse(JSON.stringify(this.dataForm));
			formData.board = formData.board.map(item => {
				if (item.id && item.room_id) {
					delete item.id;
					delete item.room_id;
				}
				return item;
			});
			formData.fixed = formData.fixed.map(item => {
				if (item.id && item.room_id) {
					delete item.id;
					delete item.room_id;
				}
				return item;
			});
			formData.pt = formData.pt.map(item => {
				if (item.id && item.room_id) {
					delete item.id;
					delete item.room_id;
				}
				return item;
			});
			return formData;

		},
		// 取消保存
		cancelSave() {
			if (this.isRenewal) {
				this.isRenewal = false
			} else {
				uni.navigateBack({
					delta: 1
				});
			}
		}
	}
}
</script>

<style lang="scss" scoped>
.filter-modal {
	background: #fff;
	height: 30vh;
	border-radius: 40rpx 40rpx 0 0;
	overflow-y: scroll;

	.header {
		position: fixed;
		width: 100%;
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 40rpx;
		box-sizing: border-box;
		height: 120rpx;
		border-radius: 40rpx 40rpx 0 0;
		border-bottom: 1px solid #eee;
		background: #ffffff;
		z-index: 100;

		.confirm {
			color: #FE4F04;
		}
	}

	.fill-box {
		height: 120rpx;
	}

	.section-box {
		padding: 0 20rpx;
		margin: 20rpx 0 40rpx;

		.title {
			font-size: 28rpx;
			color: #222222;
			font-weight: 600;
			margin-bottom: 20rpx;
		}

	}

	.tags-box {
		display: flex;
		flex-wrap: wrap;
		gap: 20rpx;

		.tag-item {
			font-size: 28rpx;
			height: 68rpx;
			line-height: 68rpx;
			padding: 0rpx 50rpx;
			border-radius: 40rpx;
			background: #F5F6FA;
			border: 1rpx solid #F5F6FA;
		}

		.tag-item.active {
			color: #FF7D41;
			background: #FFF6ED;
			border: 1rpx solid #FE4F04;
		}
	}
}

/* 底部操作菜单 */
.page-bottom {
	position: fixed;
	width: 100%;
	bottom: 0rpx;
	z-index: 200;
	display: flex;
	justify-content: space-around;
	align-items: center;
	background: #ffffff;
	border-radius: 16rpx;
	padding: 20rpx;
	box-sizing: border-box;

	button {
		margin: unset;
		padding: unset;
		background-color: #ffffff;
	}

	button::after {
		border: none;
	}

	.icon-box {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		font-size: 22rpx;
		color: #333333;
		margin-right: 48rpx;

		.label {
			font-size: 22rpx;
			color: #333333;
			margin-top: 6rpx;
		}
	}

	.action-btn-group {
		display: flex;
		align-items: center;
		justify-content: center;
		overflow: hidden;
		flex: 1;

		.action-btn1,
		.action-btn2 {
			width: 100%;
			height: 88rpx;
			font-weight: bold;
			font-size: 30rpx;
			line-height: 88rpx;
			text-align: center;
			border-radius: 44rpx;
			border: 2rpx solid #FE4F04;
		}

		.action-btn1 {
			color: #FE4F04;
			background: #fff;
			margin-right: 10rpx;
		}

		.action-btn2 {
			color: #fff;
			background: #FE4F04;
			margin-left: 10rpx;
		}

	}
}

.edit-page {
	width: 100%;
	min-height: 100vh;
	background-color: #F7F8FA;
	position: relative;

	.contentBox {
		padding-bottom: 40rpx;
	}
}

.form-switch {
	margin-top: 40rpx;
	display: flex;
	align-items: center;
	justify-content: space-between;
}

.form-title {
	font-weight: bold;
	font-size: 26rpx;
	color: #2A0C00;
	margin: 24rpx 72rpx;
	display: flex;
	align-items: center;
	justify-content: space-between;
}

.form-list {
	padding: 34rpx 40rpx;
	border-radius: 16rpx;
	margin: 20rpx 32rpx;
	background: #FFFFFF;

	.form-item,
	.form-item1 {
		.title {
			width: 200rpx;
			font-size: 28rpx;
			color: #666666;
		}

		.required::after {
			content: '*';
			color: #FE4F04;
			padding-left: 10rpx;
			font-size: 28rpx;
			font-weight: bold;
		}

		.unit {
			font-size: 28rpx;
			color: #222222;
			margin-left: 20rpx;
		}

		.input {
			flex: 1;
			text-align: right;
		}

		.value-box {
			display: flex;
			align-items: center;
			justify-content: flex-end;
			flex: 1;
			margin-left: 10rpx;

			.value-info {
				font-size: 28rpx;
				color: #222222;
			}
		}

	}

	.form-item {
		height: 100rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;
	}

	.form-item1 {
		margin-top: 20rpx;
	}

	.form-item:last-child {
		border-bottom: 0;
	}
}

.select-box {
	background: #FFFFFF;
	padding: 34rpx 40rpx;
	border-radius: 16rpx;
	margin: 20rpx 32rpx;

	.select-title {
		display: flex;
		align-items: center;
		justify-content: space-between;
		font-weight: bold;
		font-size: 26rpx;
		color: #2A0C00;

		.icon-select {
			width: 48rpx;
			height: 48rpx;
		}

		.input {
			flex: 1;
			text-align: right;
		}
	}

	.select-list {
		.select-item {
			display: flex;
			align-items: center;
			justify-content: space-between;
			height: 100rpx;
			margin-top: 20rpx;

			.item-left {
				font-size: 28rpx;
				color: #666666;
			}

			.item-right {
				display: flex;
				align-items: center;

				.item-text {
					font-size: 28rpx;
					color: #222222;
					margin-right: 10rpx;
				}
			}
		}
	}
}

.date-type-box {
	//网格布局一行三个
	display: grid;
	grid-template-columns: repeat(3, 1fr);
	grid-gap: 20rpx;
	background: #F5F6FA;
	border-radius: 16rpx;
	padding: 20rpx 30rpx;

	.date-type-item {
		display: flex;
		align-items: center;
		font-size: 28rpx;
		padding: 10rpx 0;

		.icon-select {
			width: 36rpx;
			height: 36rpx;
			margin-right: 20rpx;
		}
	}
}

::v-deep .u-tag-wrapper {
	margin: 10rpx;
}

::v-deep .u-tag--primary--plain {
	border-color: #999 !important;
}

::v-deep .u-tag__text--primary--plain {
	color: #999 !important;
}
</style>